package cn.laixueit.controller;

import cn.laixueit.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/student")
public class StudentController {



    @RequestMapping("/findall")
    public String findAll(){
        System.out.println("查所有");
        return "index";
    }


    @RequestMapping("/save")
    public ModelAndView save(Student student, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        HttpSession session = request.getSession();
        String realPath = session.getServletContext().getRealPath("img");


        ModelAndView modelAndView = new ModelAndView();

//        System.out.println(student);
//        System.out.println(file.getOriginalFilename());

        student.setId((int)(Math.random()*10));

        File dirfile = new File(realPath);
        if(!dirfile.exists()){
            dirfile.mkdirs();
        }


        File f = new File(dirfile, file.getOriginalFilename());
        file.transferTo(f);

//        File f2 = new File("d:\\img\\a.jpg");
//        file.transferTo(f2);


        modelAndView.addObject("student",student);

        modelAndView.addObject("img",file.getOriginalFilename());

        modelAndView.setViewName("student");


        return modelAndView;
    }

}
